package com.love.netty.demo.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter ;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: FirstServerHandler
 * @Description: 逻辑处理器
 * @Author: wuj
 * @Date: 2021-06-23 09:58
 **/
public class FirstServerHandler extends ChannelInboundHandlerAdapter  {


    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // ... 收数据逻辑省略

        // 回复数据到客户端
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println(sdf.format(new Date()) + ": 蓝染听到黑崎一护说： -> " + byteBuf.toString(Charset.forName("utf-8")));
        System.out.println(sdf.format(new Date()) + ": 服务端回复回话");
        ByteBuf out = getByteBuf(ctx);
        ctx.channel().writeAndFlush(out);
    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
        byte[] bytes = "蓝染：憧憬是最遥远的距离！".getBytes(Charset.forName("utf-8"));

        ByteBuf buffer = ctx.alloc().buffer();

        buffer.writeBytes(bytes);

        return buffer;
    }
}
